<?php
namespace app\admin\controller;
use think\facade\Db;
use app\admin\model\{Product as ProductModel,Exchange,User};
use app\common\BaseController;

class Product extends BaseController{
    

    /**
     * 首页
     */
    public function index(){
        $page  = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $wheres = [];
        if(isset($search['name']) && $search['name'] !=''){
            $wheres[] = ['name','like',"%{$search['name']}%"];
        }
        $query  = ProductModel::where($wheres);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);

    }

       /**
     * 详情
     * @param int $id
     * @return \think\response\Json
     * @author Sam
     * @date 2022-04-26
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = ProductModel::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }

        /**
     * 添加
     * @return void
     * @author 
     * date 
     */
    public function create(){
        $data = request()->post();
            try {
                $this->validate($data, [
                    'name' => 'require',
                    'type' => 'require',
                    'out_price' => 'require',
                    'stock' => 'require',
                    'score' => 'require',
                ], [
                   'type.require'      => '类型必须',
                   'name.require'      => '名称必须',
                   'out_price.require' => '价格必须',
                   'stock.require'     => '库存必须',
                   'score.require'     => '积分必须',
                ]);
            } catch (\Exception $e) {
                json_response(0,$e->getError());
            }
            if(ProductModel::create($data)) json_response(1,'操作成功');
            json_response(0,'操作失败');
    }



    /**
     * 编辑
     * @return void
     * @author 
     * date 
     */
    public function edit(){
        $data = request()->post();
            try {
                $this->validate($data, [
                    'id' => 'require',
                    'name' => 'require',
                    'out_price' => 'require',
                    'stock' => 'require',
                    'score' => 'require',
                ], [
                    'id.require'      => 'ID必须',
                   'name.require'      => '名称必须',
                   'out_price.require' => '价格必须',
                   'stock.require'     => '库存必须',
                   'score.require'     => '积分必须',
                ]);
            } catch (\Exception $e) {
                json_response(0,$e->getError());
            }
            if(ProductModel::update($data,['id'=>$data['id']])) json_response(1,'操作成功');
            json_response(0,'操作失败');
    }





        /**
     * 删除
     * @return void
     * @author Sam
     * date 2021-07-01
     */
    public function delete(){
        $ids = param_check('ids');
        if(!$ProductModel = ProductModel::where('id','in',$ids)->select()) json_response(0,'不存在');
        if($ProductModel->delete()) json_response(1,'操作成功');
        json_response(0,'操作失败');
    }

    /**
     * 兑换记录
     * @return [type] [description]
     */
    public function exchange(){
        $page  = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $wheres = [];
        if(isset($search['user']) && $search['user'] !=''){
            $uids  = User::where('nickname','like',"%{$search['user']}%")->column('id');
            $wheres[] = ['uid','in',$uids];
        }
        if(isset($search['status']) && $search['status'] !=''){
            $wheres[] = ['status','=',$search['status']];
        }
        if(isset($search['goods']) && $search['goods'] !=''){
            $goods_ids  = ProductModel::where('name','like',"%{$search['goods']}%")->column('id');
            $wheres[] = ['goods_id','in',$goods_ids];
        }
        $query  =  Exchange::with(['user','goods'])->where($wheres);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->append(['status_text'])->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);

    }

        /**
     * 兑换记录导出
     * @return [type] [description]
     */
    public function exchange_log_export(){
        $search = request()->param();
        $wheres = [];
        if(isset($search['user']) && $search['user'] !=''){
            $uids  = User::where('nickname','like',"%{$search['user']}%")->column('id');
            $wheres[] = ['uid','in',$uids];
        }
        if(isset($search['status']) && $search['status'] !=''){
            $wheres[] = ['status','=',$search['status']];
        }
        if(isset($search['goods']) && $search['goods'] !=''){
            $goods_ids  = ProductModel::where('name','like',"%{$search['goods']}%")->column('id');
            $wheres[] = ['goods_id','in',$goods_ids];
        }
        $query  =  Exchange::with(['user','goods'])->where($wheres);
        $data   = $query->order('id desc')->append(['status_text']);
        big_array_to_csv($data, '兑换记录导出', [
            'goods_name'    => '商品名称',
            'status_text'        => '状态',
            'nickname'          => '姓名',
            'score'        => '积分',
            'number'       => '数量',
            'create_time'      => '兑换时间'
        ]);
    }


        /**
     * 发货
     * @return void
     * @author Sam
     * date 2021-12-13
     */
    public function deliver(){
        $id = \param_check('id');
        if(request()->isPost()) {
           $data = request()->post();
           $data['status'] = 2;
           if(Exchange::update($data,['id'=>$id])) json_response(1,'操作成功');
           json_response(0,'操作失败');
        }
    }


    /**
     * 审核通过 特殊场景使用 需要更改状态值 适用需要审核的兑换
     * @return [type] [description]
     */
    public function verify(){
        $id = param_check('id');
        $exchange = Exchange::find($id);
        if($exchange->status > 0) json_response(0,'状态异常');
        $exchange->status =1;
        if($exchange->save()) json_response(1,'操作成功');
        json_response(0,'操作失败');
    }

    /**
     * 审核拒绝 特殊场景使用 需要更改状态值 适用需要审核的兑换
     * @return [type] [description]
     */
    public  function refund(){
        $id = param_check('id');
        $exchange = Exchange::find($id);
        if($exchange->status > 0) json_response(0,'状态异常');
        if(request()->isPost()) {
            $reason = param_check('reason');
            try{
                $exchange->status  = 2;
                $exchange->refund_reason = $reason;
                $exchange->save();
                Exchange::in_score($exchange->uid,$exchange->score,3,$id);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
            }
            json_response(1,'操作成功');
         }else{
            return $this->render_form([
              
                ['type'=>'textarea', 'name'=>'reason', 'title'=>'拒绝理由', 'lay-verify'=>'required'],
                
            ]);
         }
    }

    
}